package com.pansoft.openplanet.activity;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.ResStringUtil;
import com.pansoft.nfc.mifare.Common;
import com.pansoft.nfc.mifare.activity.MifareDeleteColdWalletActivity;
import com.pansoft.nfc.mifare.activity.MifareNfcMessageActivity;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.account.util.ActAccountGenerator;
import com.pansoft.openplanet.activity.child.CreateEosWalletActivity;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.util.PrivateKeyUtils;
import com.pansoft.openplanet.util.TCAccountManager;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.ExportPrivateKeyDialog;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.utilcode.util.KeyboardUtils;
import com.utilcode.util.StringUtils;
import com.utilcode.util.ToastUtils;
import com.utilcode.util.UriUtils;

import net.sf.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.AfterPermissionGranted;

import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_CUT;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_GALLERY;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_TAKEPHOTO;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * 星际资产钱包详情页
 *
 * @author yqs
 */
public class IPAssetsWalletDetailActivity extends TCBaseActivity implements View.OnClickListener {

    private static final String TAG = "IPAssetsWalletDetailAct";
    private RelativeLayout rlLayout1;
    private ImageView ivIcon;
    private TextView tvWalletName;
    private TextView tvWalletAddress;
    private RelativeLayout rlLayout2;
    private ImageView ivAvatar;
    private RelativeLayout rlLayout3;
    private LinearLayout mLlHdRoot;
    private TextView tvShowname;
    private Button butDelete;
    private ConstraintLayout backPrivateLayout,mClAddressList,mClCopyPubkey;
    //激活或者更换主账户，只有eos显示
    private ConstraintLayout clActive;
    private ImageView ivActive;
    private TextView tvActive;

    private TextView tvConvert;

    private String pictureUrlPath;//头像在网络上的位置
    private PictureAndCropManager pictureAndCropManager;//拍照裁剪
//    private SelectAvatarDialog selectAvatarDialog;

    private Account account;
    private String address;
    private AccountDao accountDao;
    private String[] items;//账户名

    public static void start(Context context, String address) {
        Intent starter = new Intent(context, IPAssetsWalletDetailActivity.class);
        starter.putExtra("address", address);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_update_wallet_avatar_name);
        address = getIntent().getStringExtra("address");
        pictureAndCropManager = new PictureAndCropManager(this);
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
        dismissLoading();
    }

    private void initView() {
        TextView tvName = (TextView) findViewById(R.id.tv_title);
        tvName.setText(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_management));
        rlLayout1 = (RelativeLayout) findViewById(R.id.rl_layout1);
        ivIcon = (ImageView) findViewById(R.id.iv_icon);
        tvWalletName = (TextView) findViewById(R.id.tv_wallet_name);
        tvWalletAddress = (TextView) findViewById(R.id.tv_wallet_address);
        rlLayout2 = (RelativeLayout) findViewById(R.id.rl_layout2);
        ivAvatar = (ImageView) findViewById(R.id.iv_avatar);
        rlLayout3 = (RelativeLayout) findViewById(R.id.rl_layout3);
        tvShowname = (TextView) findViewById(R.id.tv_showname);
        butDelete = (Button) findViewById(R.id.but_delete);
        backPrivateLayout = (ConstraintLayout) findViewById(R.id.cl_backup_private_key);
        mClCopyPubkey = (ConstraintLayout) findViewById(R.id.cl_copy_pubkey);
        mLlHdRoot = (LinearLayout) findViewById(R.id.ll_hd_root);
        clActive = (ConstraintLayout) findViewById(R.id.cl_active);
        ivActive = (ImageView) findViewById(R.id.iv_active);
        tvActive = (TextView) findViewById(R.id.tv_active);
        mClAddressList = (ConstraintLayout) findViewById(R.id.cl_address_list);
        mClAddressList.setOnClickListener(this);
        mClCopyPubkey.setOnClickListener(this);
        clActive.setOnClickListener(this);
        backPrivateLayout.setOnClickListener(this);
        butDelete.setOnClickListener(this);
        rlLayout2.setOnClickListener(this);
        rlLayout3.setOnClickListener(this);
        tvConvert = (TextView) findViewById(R.id.tv_convert);
        findViewById(R.id.cl_convert).setOnClickListener(this);
//        ivIcon = (ImageView) findViewById(R.id.iv_icon);
//        etName = (EditText) findViewById(R.id.et_name);
//        tvSetAvatar = (Button) findViewById(R.id.tv_set_avatar);
//        ivIcon.setOnClickListener(this);
//        tvSetAvatar.setOnClickListener(this);
    }

    private void initData() {
//        selectAvatarDialog = new SelectAvatarDialog(this, pictureAndCropManager);
        accountDao = new AccountDao(this);
        account = accountDao.getAccount(address);
        if (account != null) {
            tvWalletName.setText(account.getAcccountName());
            if (account.getBlockChainName().equals(EosNetParamUtil.getEosChainName()) && !account.isActivate()) {
                tvWalletAddress.setTextColor(getResources().getColor(R.color.op_text_yellow_color));
                tvWalletAddress.setText(getString(R.string.to_be_activated));
            } else {
                tvWalletAddress.setTextColor(getResources().getColor(R.color.op_text_sub_color));
                tvWalletAddress.setText(account.getSimpleAddress());
            }
            if (account.getAccountAvatar() == null || account.getAccountAvatar().equals("")) {
                LXGlideImageLoader.getInstance().displayRoundCornerImage(IPAssetsWalletDetailActivity.this, ivAvatar,
                        R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                LXGlideImageLoader.getInstance().displayRoundCornerImage(IPAssetsWalletDetailActivity.this, ivIcon,
                        R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
            } else {
                LXGlideImageLoader.getInstance().displayRoundCornerImage(IPAssetsWalletDetailActivity.this,
                        ivAvatar, account.getAccountAvatar(), R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                LXGlideImageLoader.getInstance().displayRoundCornerImage(IPAssetsWalletDetailActivity.this,
                        ivIcon, account.getAccountAvatar(), R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
            }
            tvShowname.setText(account.getAcccountName());
            if (account.getBlockChainName().equals(EosNetParamUtil.getEosChainName())) {
                findViewById(R.id.cl_convert).setVisibility(View.GONE);
                //eos显示激活或者更换主账户
                clActive.setVisibility(View.VISIBLE);
                if (account.isActivate()) {
                    tvActive.setText(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_switch_account));
                    ivActive.setImageDrawable(getResources().getDrawable(R.drawable.eos_change_account));
                }
            }
            if (account.getAccountType() == Account.ACCOUNT_TYPE_COMMON) {
                tvConvert.setText(R.string.op_convert_to_cold_wallet);
            } else if (account.getAccountType() == Account.ACCOUNT_TYPE_COLD) {
                tvConvert.setText(R.string.op_convert_to_hot_wallet);
                findViewById(R.id.cl_backup_private_key).setVisibility(View.GONE);
            } else {
                findViewById(R.id.cl_convert).setVisibility(View.GONE);
            }
            if (account.getAddress().equals(account.getMainAccoutAddress())) {
                //默认eth，不可删除, 不可转换
                butDelete.setVisibility(View.GONE);
                findViewById(R.id.cl_convert).setVisibility(View.GONE);
            }

            if(account.getBlockChainName().equals(IPAssetsConstant.ChainEnum.BTC.chainName)){
                if(!StringUtils.isEmpty(account.getHdBtcCurrentChildAddress())){
                    mLlHdRoot.setVisibility(View.VISIBLE);
                }

            }
        }

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rl_layout2) {
            showPhotoDialog();
        } else if (id == R.id.rl_layout3) {
            showNameAlert();
            //pictureUrlPath = pictureUrlPath == null ? "" : pictureUrlPath;


        } else if (id == R.id.but_delete) {
            deleteWalletDialog();
        } else if (id == R.id.cl_backup_private_key) {
            PassWordAlertDialog dialog = new PassWordAlertDialog(IPAssetsWalletDetailActivity.this,
                    new PassWordAlertDialog.OnEnterClick() {
                        @Override
                        public void passVerifySuccess(String passWord) {
                            coverPrimaryKey(account.getFileName());
                        }
                    });
            dialog.show();
        } else if (id == R.id.cl_active) {
            if (account.isActivate()) {
                //更换主钱包
                changeMainAccountAlert();
            } else {
                //跳转分享二维码激活
                Intent intent = new Intent(this, CreateEosWalletActivity.class);
                intent.putExtra("active_pub_key", account.getEosActivePubKey());
                intent.putExtra("wallet_name", account.getAcccountName());
                intent.putExtra("wallet_avatar", account.getAccountAvatar());
                startActivity(intent);
            }
        } else if (id == R.id.cl_convert) {
            //冷热钱包转换
            //直接读取NFC
            if (!EnvSupportManager.isSupportNfcWallet() && !EnvSupportManager.isSupportForceBleNfc()) {
                return;
            }
            if (!EnvSupportManager.isSupportForceBleNfc() && Common.hasMifareClassicSupport(this)){
                MifareNfcMessageActivity.start(IPAssetsWalletDetailActivity.this,
                        account.getAddress(), BleBlutoothScanActivity.TYPE_CONVERT_WALLET);
            } else {
//                //蓝牙读卡器
                BleBlutoothScanActivity.start(IPAssetsWalletDetailActivity.this,
                        account.getAddress(), BleBlutoothScanActivity.TYPE_CONVERT_WALLET,
                        BleBlutoothScanActivity.BLE_TYPE_NFC);
            }
        }else if(id == R.id.cl_address_list){
            //跳转钱包地址列表
            AssetWalletAddressListActivity.start(this,account);
        }else if(id == R.id.cl_copy_pubkey){
            //复制钱包公钥
            copyAddress(account.getPublicKey());
        }
    }

    private void showPhotoDialog() {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.alertdialog);
        // 为确认按钮添加事件,执行退出应用操作
        TextView tv_paizhao = (TextView) window.findViewById(R.id.tv_content1);
        tv_paizhao.setText(R.string.common_text_take_picture);
        tv_paizhao.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("SdCardPath")
            public void onClick(View v) {
                dlg.cancel();
                startTakePhoto();
            }
        });
        TextView tv_xiangce = (TextView) window.findViewById(R.id.tv_content2);
        tv_xiangce.setText(R.string.common_text_photo_album);
        View lineView = window.findViewById(R.id.line1);
        lineView.setVisibility(View.VISIBLE);
        tv_xiangce.setVisibility(View.VISIBLE);
        tv_xiangce.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pictureAndCropManager.selectPhoto();
                dlg.cancel();
            }
        });

    }

    private void changeMainAccountAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        int checkedItem = 0;
        if (account.getEosAccountNames() == null || account.getEosAccountNames().equals("")) {
            items = new String[]{account.getAddress()};
        } else {
            items = account.getEosAccountNames().split("_");

            for (int i = 0; i < items.length; i++) {
                if (account.getAddress().equals(items[i])) {
                    checkedItem = i;
                }
            }
        }

        builder
                .setTitle(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_select_account))
                .setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        accountDao.updateEosAccountName(account.getAddress(), items[i]);
                        tvWalletAddress.setText(items[i]);
                        dialogInterface.dismiss();
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_CAMERA)
    private void startTakePhoto() {
        if (EasyPermissionUtils.checkCameraPermission()) {
            pictureAndCropManager.takePicture();
        } else {
            EasyPermissionUtils.requestCameraPermission(this);
        }
    }

    //删除钱包
    private void deleteWalletDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.common_text_hint)
                .setMessage(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_remove_wallet))
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (account.getAccountType() != Account.ACCOUNT_TYPE_COLD) {
                            if (account.isMaster()) {
                                ToastUtil.showToast(IPAssetsWalletDetailActivity.this, ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_main_not_allowed));
                                return;
                            }
                            deleteFromServer();
                        } else {
                            //冷钱包
                            Intent intent;
                            if (!EnvSupportManager.isSupportNfcWallet() && !EnvSupportManager.isSupportForceBleNfc()) {
                                return;
                            }
                            if (!EnvSupportManager.isSupportForceBleNfc() && Common.hasMifareClassicSupport(IPAssetsWalletDetailActivity.this)){
                                intent = new Intent(IPAssetsWalletDetailActivity.this, MifareDeleteColdWalletActivity.class);
                            } else {
                                intent = new Intent(IPAssetsWalletDetailActivity.this, BleBlutoothScanActivity.class);
                                intent.putExtra("createType", BleBlutoothScanActivity.TYPE_DELETE_COLD_CHILD_WALLET);
                            }
                            intent.putExtra("address", address);
                            intent.putExtra("cardNo", account.getColdWalletCardUid());
                            startActivityForResult(intent, 6656);
                        }
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, null).show();
    }

    private void deleteFromServer() {
        HashMap<String, String> hashMap = new HashMap<>();

        hashMap.put("accountAddress", account.getAddress());
        hashMap.put("mainAccountAddress", account.getMainAccoutAddress());
//        if (account.getBlockChainName().equals(IPAssetsConstant.ChainEnum.BTC.chainName)) {
//            hashMap.put("blockChainName", "BTC");
//        }
        hashMap.put("blockChainName", account.getBlockChainName());
        TCRequestUtil.getCommonRequest(TAG, "account/delChildrenWallet", hashMap,
                new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = JSONObject.fromObject(response);
                    if (jsonObject.optString("result", "").equals("success")) {
                        accountDao.delete(account.getAddress());
                        ToastUtil.showToast(IPAssetsWalletDetailActivity.this, ResStringUtil.getString(R.string.common_text_delete_success));
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(IPAssetsWalletDetailActivity.this, ResStringUtil.getString(R.string.common_text_delete_fails));
                }
            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(IPAssetsWalletDetailActivity.this, ResStringUtil.getString(R.string.common_text_delete_fails));
            }
        });
    }


    //名称修改
    private void showNameAlert() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        RelativeLayout layout = (RelativeLayout) inflater.inflate(
                com.efounder.chat.R.layout.social_alertdialog, null);
        dialog.setView(layout);
        final EditText ed_name = (EditText) layout
                .findViewById(com.efounder.chat.R.id.ed_name);
        ed_name.setText(account.getAcccountName());
        ed_name.setSelection(ed_name.getText().length());
        dialog.setTitle(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_enter_wallet_name));
        dialog.setPositiveButton(R.string.common_text_confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        String newName = ed_name.getText().toString().trim();
                        if (TextUtils.isEmpty(newName)) {
                            return;
                        } else {
                            //调用接口
                            updateWalletInfo("accountName", newName);
                        }
                        dialog.cancel();
                    }


                });

        dialog.setNegativeButton(R.string.common_text_cancel, null);
        dialog.show();

        ed_name.post(new Runnable() {
            @Override
            public void run() {
                KeyboardUtils.showSoftInput(ed_name);
            }
        });
    }

    @SuppressLint("SdCardPath")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
                    pictureAndCropManager.startPhotoZoom(UriUtils.getUriForFile(
                            new File(pictureAndCropManager.getPicturePath())), 300);
                    break;

                case PHOTO_REQUEST_GALLERY:
                    if (data != null) {
                        pictureAndCropManager.startPhotoZoom(data.getData(), 300);
                    }
                    break;

                case PHOTO_REQUEST_CUT:
                    Log.i(ResStringUtil.getString(R.string.chat_cut_after_path), pictureAndCropManager.getPicturePath());
                    if (!isNetActive()) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_network_error_please_again);
                        return;
                    }
                    showLoading(ResStringUtil.getString(R.string.common_text_uploading));

                    try {
                        PansoftCloudUtil.getCloudRes(pictureAndCropManager.getPicturePath(), new PansoftCloudUtil.UpLoadListener() {
                            @Override
                            public void getHttpUrl(Boolean isSuccess, String url) {
                                dismissLoading();
                                if (isSuccess) {
//                                    Log.i("MyUserInfoActivity", "---头像在云盘服务器上的路径:" + url);
                                    pictureUrlPath = url;
                                    pictureUrlPath.trim();
                                    //ToastUtil.showToast(getApplicationContext(), "上传成功");

                                    updateWalletInfo("accountIcon", pictureUrlPath);

                                } else {
                                    ToastUtil.showToast(getApplicationContext(), ResStringUtil.getString(R.string.common_text_upload_fail_again));
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
                case 6656:
                    finish();
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 修改头像或名称
     *
     * @param key
     * @param value
     */
    private void updateWalletInfo(final String key, final String value) {

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put(key, value);
        hashMap.put("accountAddress", account.getAddress());
        hashMap.put("mainAccountAddress", account.getMainAccoutAddress());
        if (account.getBlockChainName().equals(IPAssetsConstant.ChainEnum.BTC.chainName)) {
            hashMap.put("blockChainName", "BTC");
        }
        if (account.getBlockChainName().equals(IPAssetsConstant.ChainEnum.ETE.chainName)) {
            hashMap.put("blockChainName", "ETE");
        }
        TCRequestUtil.getCommonRequest(TAG, "account/updateChildrenWallet", hashMap,
                new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = JSONObject.fromObject(response);
                    if (jsonObject.optString("result", "").equals("success")) {
                        if (key.equals("accountName")) {
                            tvShowname.setText(value);
                            tvWalletName.setText(value);
                            account.setAcccountName(value);
                            accountDao.insertOrReplace(account);
                        } else {
                            LXGlideImageLoader.getInstance().displayRoundCornerImage(IPAssetsWalletDetailActivity.this,
                                    ivAvatar, pictureUrlPath, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);
                            LXGlideImageLoader.getInstance().displayRoundCornerImage(IPAssetsWalletDetailActivity.this,
                                    ivIcon, pictureUrlPath, R.drawable.star_asset_default_wallet_icon, R.drawable.star_asset_default_wallet_icon, 20);

//                            LXGlideImageLoader.getInstance().displayImage(IPAssetsWalletDetailActivity.this,
//                                    ivAvatar, pictureUrlPath);
                            account.setAccountAvatar(value);
                            accountDao.insertOrReplace(account);
                        }
                        ToastUtil.showToast(IPAssetsWalletDetailActivity.this, ResStringUtil.getString(R.string.open_planet_change_success));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(IPAssetsWalletDetailActivity.this, ResStringUtil.getString(R.string.open_planet_change_fail));
                }
            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(IPAssetsWalletDetailActivity.this, ResStringUtil.getString(R.string.open_planet_change_fail));
            }
        });
    }


    //备份私钥
    private void coverPrimaryKey(final String filePath) {

        if (account.getBlockChainName().equals(IPAssetsConstant.ChainEnum.BTC.chainName)) {
            backupBtcPrivateKey(filePath);
        } else if (account.getBlockChainName().equals(IPAssetsConstant.ChainEnum.ETE.chainName)) {
            backupEthPrivateKey(filePath);
        } else if (account.getBlockChainName().equals(IPAssetsConstant.ChainEnum.ETH.chainName)) {
            backupEthPrivateKey(filePath);
        } else if (account.getBlockChainName().equals(EosNetParamUtil.getEosChainName())) {
            backupEosPrivateKey(account.getSecretPrivateKey(), account.getEosActivePriKey());
        } else if (account.getBlockChainName().equals(IPAssetsConstant.ChainEnum.ACHAIN.chainName)) {
            backupACTPrivateKey(account.getAddress());
        }
    }

    /**
     * 备份eos 私钥
     *
     * @param secretPrivateKey
     */
    private void backupEosPrivateKey(final String secretPrivateKey, final String eosActivePrivateKey) {
        Disposable disposable = Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(final ObservableEmitter<List<String>> emitter) throws Exception {
                List<String> list = new ArrayList<>();
                String key = PrivateKeyUtils.exportEosPrivateKey(secretPrivateKey, "");
                String eosActiveKey = PrivateKeyUtils.exportEosPrivateKey(eosActivePrivateKey, "");
                list.add(key);
                list.add(eosActiveKey);
                emitter.onNext(list);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                showLoading(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_generating_private_key));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<String>>() {
            @Override
            public void accept(List<String> list) throws Exception {
                dismissLoading();
                ExportPrivateKeyDialog dialog = new ExportPrivateKeyDialog(IPAssetsWalletDetailActivity.this);
                dialog.setMessage(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_owner_private_key)+"\n" + list.get(0)
                        + "\n"+ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_active_private_key)+"\n" + list.get(1));
                dialog.show();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                dismissLoading();
                ToastUtil.showToast(getApplicationContext(), ResStringUtil.getString(R.string.open_planet_get_private_key_fail));
            }
        });
        addDisposable(disposable);
    }

    //备份btc 钱包私钥
    private void backupBtcPrivateKey(final String filePath) {
        Disposable disposable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(final ObservableEmitter<String> emitter) throws Exception {

                String key = PrivateKeyUtils.exportBtcPrivateKey(filePath, "");
                emitter.onNext(key);
                emitter.onComplete();

            }
        }).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                showLoading(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_generating_private_key));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                dismissLoading();
                ExportPrivateKeyDialog dialog = new ExportPrivateKeyDialog(IPAssetsWalletDetailActivity.this);
                dialog.setMessage(s);
                dialog.show();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                dismissLoading();
                ToastUtil.showToast(getApplicationContext(), ResStringUtil.getString(R.string.open_planet_get_private_key_fail));
            }
        });
        addDisposable(disposable);

    }

    //备份eth 钱包私钥
    private void backupEthPrivateKey(final String filePath) {
        Disposable disposable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(final ObservableEmitter<String> emitter) throws Exception {
                if (filePath == null) {
                    //throw  new RuntimeException("失败");
                    TCAccountManager tcAccountManager = new TCAccountManager(IPAssetsWalletDetailActivity.this);
                    List<Account> accounts = new ArrayList<>();
                    accounts.add(account);
                    tcAccountManager.restoreByRXjava(accounts, new TCAccountManager.AccountManagerListener() {
                        @Override
                        public void onSuccess(Object object) {
                            String key = PrivateKeyUtils.exportPrivateKey(account.getFileName(), "");
                            emitter.onNext(key);
                            emitter.onComplete();
                        }

                        @Override
                        public void onFail(String fail) {
                            throw new RuntimeException(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_running_time_error));
                        }
                    });
                } else {
                    String key = PrivateKeyUtils.exportPrivateKey(filePath, "");
                    emitter.onNext(key);
                    emitter.onComplete();
                }

            }
        }).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                showLoading(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_generating_private_key));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                dismissLoading();
                ExportPrivateKeyDialog dialog = new ExportPrivateKeyDialog(IPAssetsWalletDetailActivity.this);
                dialog.setMessage(s);
                dialog.show();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                dismissLoading();
                ToastUtil.showToast(getApplicationContext(), ResStringUtil.getString(R.string.open_planet_get_private_key_fail));
            }
        });
        addDisposable(disposable);
    }

    //备份ACT 钱包私钥
    private void backupACTPrivateKey(String address) {
        showLoading(ResStringUtil.getString(R.string.open_planet_asset_ip_wallet_detail_generating_private_key));
        Disposable disposable = ActAccountGenerator.backUpPrivateKey(address, new ActAccountGenerator.BackUpPrivateKeyListener() {
            @Override
            public void backUpSuccess(String privateKey) {
                dismissLoading();
                ExportPrivateKeyDialog dialog = new ExportPrivateKeyDialog(IPAssetsWalletDetailActivity.this);
                dialog.setMessage(privateKey);
                dialog.show();
            }

            @Override
            public void onfail(String msg) {
                dismissLoading();
                ToastUtil.showToast(getApplicationContext(), msg);
            }
        });
        addDisposable(disposable);
    }


    /**
     * 复制地址
     *
     * @param address 地址
     */
    private void copyAddress(String address) {
        //复制账号
        ClipboardManager cm = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setText(address);
//        ToastUtils.setBgColor(getResources().getColor(R.color.black));
//        ToastUtils.setMsgColor(getResources().getColor(R.color.op_text_white_color));
//        ToastUtils.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 150);
        ToastUtils.showShort(ResStringUtil.getString(R.string.open_planet_asset_child_wallet_list_copied_clipboard));
    }
}
